﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.MeetingRooms;
using MediatR;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.MeetingRooms
{
    public class DelRoomCommandHandler : IRequestHandler<DelRoomCommand, APIResult<int>>
    {
        private readonly IBaseRepository<MeetingRoom> _mrRep;
        private readonly ILogger<DelRoomCommandHandler> _logger;

        public DelRoomCommandHandler(IBaseRepository<MeetingRoom> mrRep, ILogger<DelRoomCommandHandler> logger)
        {
            _mrRep = mrRep;
            _logger = logger;
        }

        public async Task<APIResult<int>> Handle(DelRoomCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var room = await _mrRep.GetByIdAsync(request.MeetingRoomId);
                if (room == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.MeetingRoomId} 的会议室");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "未找到指定的会议室",
                        Data = 0
                    };
                }

                // 直接调用仓储层的删除方法进行物理删除 (实际上 BaseRepository 的 Del 实现了软删除)
                await _mrRep.Del(request.MeetingRoomId);

                _logger.LogInformation($"成功删除会议室: ID {request.MeetingRoomId}");
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "删除成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"删除会议室时发生错误: ID {request?.MeetingRoomId}");
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "删除会议室失败",
                    Data = 0
                };
            }
        }
    }
}
